<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Media;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use EasyWeChat\Kernel\Messages\Article;
use Log;
use EasyWeChat\Factory;
use App\Repos\UserRepo;
use App\Models\Order;
use function EasyWeChat\Kernel\Support\generate_sign;

class WechatController extends Controller
{
    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $app = app('wechat.official_account');
        //dd($app);
        $app->server->push(function($message){
         
            //return "欢迎关注!业务问题请加微信 bzs1984 咨询，谢谢。";        
           return env('WELCOME_MSG', '欢迎关注!');
            
        });

        return $app->server->serve();
    }

    public function createMenu()
    {
        $app = app('wechat.official_account');
        $buttons = [
           
                    [
                        "type" => "view",
                        "name" => "提交工单",
                        "url"  => config('app.url')."/user/task/create"
                    ],
                    [
                        "type" => "view",
                        "name" => "我的工单",
                        "url"  => config('app.url')."/user/task/"
                    ]  
                   
            
           
        ];
        $rs = $app->menu->create($buttons);
        if($rs['errcode']==0) {
            return response()->json(['status'=>'success','msg'=>'操作成功']);
        } 
        return response()->json(['status'=>'danger','msg'=>$rs['errmsg']]);
    }

    public function getMaterial($type='image')
    {
        $app = app('wechat.official_account');
        // 图片素材
        $list = $app->material->list('image', 0, 10);

        // 图文素材
        //$list = $app->material->list('news', 0, 10);

        return view('admin.material.index');
    }

    public function wxLogin(Request $request)
    {
        $wechat_user =  session('wechat.oauth_user.default');
        $openId = $wechat_user->id;
        $app = app('wechat.official_account');
        $user = $app->user->get($openId);
           
        // 获取 OAuth 授权结果用户信息
       
        $data['unionid']  = array_get($user,'unionid');
        $data['nickname'] = $user['nickname'];
        
        $data['sex']            = array_get($user,'sex')==1?'男':'女';
        $data['wx_openid']      = $openId;
        $data['wx_info']        = json_encode($user);
        $data['remember_token'] = str_random(16);

        Log::info('微信登录：'.json_encode($user));
        $user = UserRepo::create($data);
        if($user) {
                    
             
            $url = config('app.url').'/wx/index.html?code='.$user->remember_token;
            return redirect($url);
               
        }
        $rs['status'] = false;
        $rs['msg'] = '注册失败';
        return response()->json($rs);
    }

    public function makeOrder(Request $request)
    {
        $rs['status'] = false;
        $config = config('wechat.payment.default');  
        $payment = Factory::payment($config);
        $jssdk = $payment->jssdk;
      
        $code = date('YmdHis').mt_rand(1000,9999);
       
        
        try {
           
            $data['user_id']     = $request->user_id;          
            $data['product_id']  = object_get($request,'product_id');      
            $data['total_amount']   = $request->money;          
            $data['code']        = $code;
            $flag = Order::create($data);
            if($flag) {
              $time = time();
                $app = app('wechat.payment');
                $result = $app->order->unify([
                    'body' => '积分充值',
                    'out_trade_no' => $code,
                    'total_fee'    => (int)$request->money,               
                    'trade_type' => 'JSAPI',
                    'openid' => $request->openid,
                    'timeStamp' => $time,
                ]);


              
                // 如果成功生成统一下单的订单，那么进行二次签名
                if ($result['return_code'] === 'SUCCESS') {
                    //dd($result);
                    $config = $jssdk->sdkConfig($result['prepay_id']); // 返回数组
                    $rs['config'] = $config;

                    // 二次签名的参数必须与下面相同
                    $params = [
                        'appId'     => config('wechat.official_account.default.app_id'),
                        'timeStamp' => $time,
                        'nonceStr'  => $result['nonce_str'],
                        'package'   => 'prepay_id='.$result['prepay_id'],
                        'signType'  => 'MD5',
                    ];
                    // config('wechat.payment.default.key')为商户的key
                    $params['paySign'] = generate_sign($params, config('wechat.payment.default.key'));
                    $params['signJs'] = $result['sign'];

                    $params['order_code']    = $code;
                    $params['appId'] = config('wechat.official_account.default.app_id');
                    $params['order_created'] = date('Y-m-d H:i:s');
                    $params['total_fee'] = (int)$request->money;
                    
                    $rs['data'] = $params;
                    $rs['status'] = true;
                    Log::info('二次签名:'.json_encode($params));
                    return response()->json($rs);
                }
                $rs['data'] = $result;
                $rs['status'] = true;
                return response()->json($rs);  
            
  
            } 
            $rs['msg'] = '保存订单失败';
            return response()->json($rs);    
        } catch (\Exception $e) {
            $rs['msg'] = $e->getMessage();
            return response()->json($rs);
        }
        $rs['msg'] = '充值是失败';
        return response()->json($rs);
        

        
       
    }

    
    public function payNotify()
    {
        $config = config('wechat.payment.default');     
        $app = Factory::payment($config);
        Log::info('进入回调：');
        $response = $app->handlePaidNotify(function($message, $fail){
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单

            $order = Order::where(['code'=>$message['out_trade_no']])->first();

            if (!$order || $order->pay_time) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

           

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    if(array_get($message,'total_fee')!=$order->total_amount) {
                        Log::info('微信回调订单金额'.array_get($message,'total_fee').'与系统中的订单金额.'.$order->total_amount.'数据不一致');
                        return false;
                    }
                    $order->pay_time = array_get($message,'time_end'); // 更新支付时间为当前时间
                    $order->status = '100';

                    $order->transaction_id = array_get($message,'transaction_id');

                // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->status = '0';
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            $order->save(); // 保存订单

            // 给用户加积分           
            $udata['point']      = $order->total_amount/100;
            $udata['product_id'] = $order->product_id;
            UserRepo::rechargePoint($order->user_id,$udata);
            return true; // 返回处理完成
        });

        $response->send(); // return $response;
    }
   


    
}
